<template>
  <div class="register-view">
    <h1>注册</h1>
    <LoginRegisterModal
      :visible="true"
      :isRegister="true"
      @register="handleRegister"
      @toggle="toggleMode"
      @close="redirectToHome"
    />
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import LoginRegisterModal from '../components/LoginRegisterModal.vue'

const router = useRouter()

const handleRegister = (username, password) => {
  const users = JSON.parse(localStorage.getItem('users')) || []
  const userExists = users.some(user => user.username === username)
  if (userExists) {
    alert('用户名已存在')
  } else {
    users.push({ username, password })
    localStorage.setItem('users', JSON.stringify(users))
    alert('注册成功，请登录')
    router.push('/login')
  }
}

const toggleMode = () => {
  router.push('/login')
}

const redirectToHome = () => {
  router.push('/')
}
</script>

<style scoped>
.register-view {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
</style>